package main

import (
	"flag"
	"log"

	"intelli-dl-online-logo-go/controller"
	"intelli-dl-online-logo-go/repository"
	"intelli-dl-online-logo-go/routes"
	"intelli-dl-online-logo-go/service"
	"intelli-dl-online-logo-go/utils"
	"intelli-dl-online-logo-go/utils/job"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func main() {
	// 解析命令行参数
	env := flag.String("env", "dev", "Environment to run (dev/prod)")
	flag.Parse()

	// 初始化配置
	viper.SetConfigName(*env) // 根据env参数加载对应配置文件
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./config")

	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}

	// 初始化日志
	err := utils.InitLogger(*env)
	if err != nil {
		log.Fatalf("Failed to initialize logger: %v", err)
	}
	defer utils.SyncLogger()

	// 初始化gin路由
	r := gin.Default()

	// 从配置中获取端口
	port := viper.GetString("server.port")
	if port == "" {
		port = "8080" // 默认端口
	}

	// 设置环境变量
	r.Use(func(c *gin.Context) {
		c.Set("env", *env)
		c.Next()
	})

	// 初始化MongoDB
	mongoURI := viper.GetString("mongodb.uri")
	err = utils.InitMongoDB(mongoURI)
	if err != nil {
		log.Fatalf(utils.ErrConnectMongoDB+": %v", err)
	}
	db := utils.GetMongoDB()

	// 初始化仓库
	userRepo := repository.NewUserRepositoryImpl(db)
	vipLogRepo := repository.NewUserVipLogRepositoryImpl(db)

	// 初始化控制器
	userController := controller.NewUserController()
	verifyRepo := repository.NewVerifyRepository()
	verifyService := service.NewVerifyService(verifyRepo, userRepo)
	verifyController := controller.NewVerifyController(verifyService)

	// 初始化路由
	routes.InitRoutes(r, userController, verifyController)

	// 启动VIP检查定时任务
	_ = job.StartVipCheckJob(userRepo, vipLogRepo)

	// 启动Web服务
	log.Println("Starting server with", *env, "environment on port", port)
	err = r.Run(":" + port)
	if err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
